package com.mvvm.start.base.base

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.Window
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.databinding.ViewDataBinding
import com.gyf.immersionbar.ImmersionBar
import com.zyao89.view.zloading.ZLoadingDialog
import com.zyao89.view.zloading.Z_TYPE
import androidx.appcompat.app.SkinAppCompatDelegateImpl
import androidx.lifecycle.ViewModelProvider
import com.mvvm.start.base.BaseApplication
import com.mvvm.start.base.utils.*

/**
 * @功能:
 * @Creat 2020/6/5 13:27
 * @User Lmy
 * @Compony  465008238@qq.com
 */
abstract class BaseActivity<VM : BaseViewModel, VB : ViewDataBinding>(private val factory: ViewModelProvider.Factory? = null) : AppCompatActivity() {
    protected var mContext: Activity? = null
    val viewBinding: VB by lazy(mode = LazyThreadSafetyMode.NONE) {
        getViewBinding(layoutInflater)
    }
    protected lateinit var mViewModel: VM
    protected var isFirstRequest: Boolean = true
    protected var isDisableQuickClick = true//用于标记当前Activity是否要处理快速双击

    private lateinit var loadingDialog: ZLoadingDialog
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(viewBinding.root)
        viewBinding.lifecycleOwner = this
        mViewModel = ViewModelUtils.createViewModel(this, factory, 0)
        mContext = this
        //添加灰度主题
        if (BaseApplication.isGrayTheme) setGaryTheme(window)
        initStyle()
        initView()
        initBasicsObserve()
        initObserve()
        if (isFirstRequest) {
            initData()
        }
    }

    private fun initBasicsObserve() {
        mViewModel.apply {
            toastText.observe(this@BaseActivity) {
                it.toast()
            }
            refresh.observe(this@BaseActivity) {
            }
            isLoading.observe(this@BaseActivity) {
                if (it) showProgress() else hideProgress()
            }
        }
    }


    /**
     * 初始化Activity的界面风格
     */
    @SuppressLint("ResourceType")
    open fun initStyle() {
        ImmersionBar.with(this)
            //.statusBarDarkFont(false)   //状态栏字体是深色，不写默认为亮色
            //.fitsSystemWindows(true)    //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
            //.statusBarColor(R.color.color_2C2A2A)
            .init()
        if (NavigationBar.checkDeviceHasNavigationBar(this)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.navigationBarColor = Color.parseColor("#ffffff")
                //设置状态栏
                window.decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
//                            View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or
                            View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
            }
        }

    }


    /**
     * 设置全局灰度主题
     */
    fun setGaryTheme(window: Window) {
        val paint = Paint()
        val cm = ColorMatrix()
        cm.setSaturation(0f)
        paint.colorFilter = ColorMatrixColorFilter(cm)
        window.decorView.setLayerType(View.LAYER_TYPE_HARDWARE, paint)
    }

    var editText: EditText? = null


    /**
     *初始化view
     */
    abstract fun initView()

    /**
     * 初始化订阅监听
     */
    abstract fun initObserve()

    /**
     * 初始化数据
     */
    open fun initData() {}

    override fun onDestroy() {
        super.onDestroy()
        mContext = null
        viewBinding.unbind()
    }

    /**
     * 显示加载框
     */
    open fun showProgress() {
        mContext?.let {
            if (!::loadingDialog.isInitialized) {
                loadingDialog = ZLoadingDialog(this)
                loadingDialog.apply {
                    setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE) //设置类型
                    setLoadingColor(Color.GRAY) //颜色
                    setHintText("加载中...")
                    setHintTextSize(16f) // 设置字体大小 dp
                    setHintTextColor(Color.GRAY) // 设置字体颜色
                    setDurationTime(0.5) // 设置动画时间百分比 - 0.5倍
//                setDialogBackgroundColor(Color.parseColor("#CC111111")); // 设置背景色，默认白色
                }
            }
            loadingDialog.apply {
                show()
            }
        }
    }

    /**
     * 隐藏加载框
     */
    open fun hideProgress() {
        mContext?.let {
            loadingDialog?.apply {
                dismiss()
            }
        }
    }

    //使editText点击外部时候失去焦点
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            /**
             * 处理下两次快速点击的问题
             */
            if (isDisableQuickClick) {
                isFastClick {
                    true
                }
            }
            val v = currentFocus
            if (isShouldHideInput(v, ev)) { //点击editText控件外部
                val imm =
                    getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                if (imm != null) {
                    assert(v != null)
                    closeKeyboard(v) //软键盘工具类
                    if (editText != null) {
                        editText?.clearFocus()
                    }
                }
            }
            return super.dispatchTouchEvent(ev)
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return window.superDispatchTouchEvent(ev) || onTouchEvent(ev)
    }

    open fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            editText = v
            val leftTop = intArrayOf(0, 0)
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop)
            val left = leftTop[0]
            val top = leftTop[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        return false
    }

    /**
     * 关闭软键盘
     *
     * @param view
     */
    open fun closeKeyboard(view: View?) {
        if (!isNull(view)) {
            val imm: InputMethodManager? =
                view?.context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm?.hideSoftInputFromWindow(view?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    /**
     * Skin换肤框架需要重写这个方法
     */
    override fun getDelegate(): AppCompatDelegate {
        return SkinAppCompatDelegateImpl.get(this, this)
    }

    /**
     * 处理控件多次点击的情况
     * 两次点击按钮之间的点击间隔不能少于1000毫秒
     */
    val MIN_CLICK_DELAY_TIME: Int = 1000
    var lastClickTime: Long = 0
    fun isFastClick(block: () -> Unit): Boolean {
        var flag = false
        val curClickTime = System.currentTimeMillis()
        if (curClickTime - lastClickTime >= MIN_CLICK_DELAY_TIME) {
            flag = true
        }
        lastClickTime = curClickTime
        if (flag) {
            block()
        }
        return flag
    }

}